import React from 'react';
import { Modal, Form, Row, Col, Input,  } from 'antd';
import { FormInstance } from 'antd/es/form/Form';
import { FormModalProps } from '@/types/global';
import { RoleItem } from '@/types/role';
import { formLayout, basicFormItemLangLayout, maxModalFormItemLayout } from '@/utils/commons';

type AddRoleProps<T> = FormModalProps<T> & {
}
type AddRolePropsEx<T> = Omit<AddRoleProps<T>, 'formData'>;

const FormItem = Form.Item;
const TextArea = Input.TextArea;

const AddRoleModal: React.FC<AddRolePropsEx<RoleItem>> = (props) => {

  const { colon, modalTitle, modalWidth, modalVisible, loading } = props;
  const formItemLayout = basicFormItemLangLayout;
  const formRef = React.createRef<FormInstance>();

  const onOk = () => {
    formRef.current!.validateFields().then(fieldsValue => {
      console.info(fieldsValue);
      const values = {
        ...fieldsValue
      };
      console.log('Received values of form: ', values);
      const { onHandlerOK } = props;
      if (onHandlerOK) {
        onHandlerOK({
          ...values
        });
      }
    }).catch();
  };

  const onCancel = () => {
    // 先清除form表单
    formRef.current!.resetFields();
    const { onHandlerCancel } = props;
    if (onHandlerCancel) {
      onHandlerCancel();
    }
  }

  return (
    <Modal
      title={modalTitle}
      destroyOnClose
      width={modalWidth}
      open={modalVisible}
      confirmLoading={loading}
      onOk={onOk}
      onCancel={onCancel}>
      <Form layout={formLayout} ref={formRef}>
        <Row>
          <Col span={12}>
            <FormItem label="角色编码" name='roleCode' {...formItemLayout} colon={colon}
              rules={[
                { max: 10, message: '角色编码最多允许输入10个字符' },
                { required: true, message: '角色编码必输' },
                { pattern: new RegExp(/^[A-Za-z][A-Za-z0-9]{1,50}$/, "g"), message: '角色编码只能以字母开头，由A-Za-z0-9组成，最大长度为10' }
              ]}
            >
              <Input/>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label="角色名称" name='roleName' {...formItemLayout} colon={colon}
              rules={[
                { max: 20, message: '角色名称最多允许输入20个字符' },
                { required: true, message: '角色名称必输' },
              ]}
            >
              <Input/>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={24}>
            <FormItem label="角色描述" name='roleDesc' {...maxModalFormItemLayout} colon={colon}
              rules={[
                { max: 30, message: '角色描述最多允许输入30个字符' },
                { required: true, message: '角色描述' }
              ]}
            >
              <TextArea maxLength={30} showCount />
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Modal>
  );

}

export default AddRoleModal;
